package com.example.demo.AliPay.Controller;

import com.alipay.api.AlipayApiException;
import com.example.demo.AliPay.Bean.IntegralParameter;
import com.example.demo.AliPay.Bean.Order;
import com.example.demo.AliPay.Bean.SeckillNumsParameter;
import com.example.demo.AliPay.Service.AliPayService;
import com.example.demo.AliPay.Service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Auther: csp1999
 * @Date: 2020/11/13/21:47
 * @Description: 支付宝沙箱测试 controller
 */
@RestController
public class SeckillController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private AliPayService aliPayService;


    /*
     * 支付宝支付 api
     */
    @PostMapping(value = "/seckill/alipay")
    public String alipay(String username, String shopname, Integer product_id, String category, String title, Integer product_nums, String outtradeno, Double price, String status, Integer integral,Integer seckill_id) throws AlipayApiException {
        String startTimeById = orderService.getStartTimeById(seckill_id);
        Date dNow = new Date( );
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = ft.format(dNow);
        if (format.compareTo(startTimeById) >= 0){
            int seckillNums = orderService.getSeckillNums(seckill_id);
            if(seckillNums > 0){
                int nowseckillNums = seckillNums-1;
                SeckillNumsParameter seckillNumsParameter = new SeckillNumsParameter();
                seckillNumsParameter.setId(seckill_id);
                seckillNumsParameter.setNums(nowseckillNums);
                orderService.updateSeckillNums(seckillNumsParameter);
                Order order = new Order();
                order.setId(product_id);
                order.setCategory(category);
                order.setSubject(title);
                order.setProduct_nums(product_nums);
                order.setOut_trade_no(outtradeno);
                order.setTotal_amount(price);
                order.setStatus(status);
                order.setUsername(username);
                order.setShopname(shopname);
                orderService.insertOrders(order);
                IntegralParameter integralParameter = new IntegralParameter();
                integralParameter.setUsername(username);
                integralParameter.setIntegral(integral);
                orderService.updateintegral(integralParameter);
                return aliPayService.aliPay(order);
            }else {
                return "没货了";
            }
        }else {
            return "Fuck You";
        }
    }

}

